Ranaco
#

Introduction

Blockchain, a technology that came into the picture after years of research, learning, and development, holds the power to change how we perceive the management and storage of data and security in general. Although now that we have a clear idea of how this “thing” should work, it's pretty easy to create one of our own 😉. Just to not make things unperceivable, let's first understand how blockchain works.

How it works?

Blockchain, as the word suggests, is a chain of blocks. Now what are the blocks? What is the chain? How does the chain connect these “blocks”? Let's understand this with an example.

Storytime

Bob the builder gets an order to build a house. Bob, along with his workers, gets to the site and starts the work. His team is being paid monthly and he keeps track of those payments in his notebook. Let's fast forward to a year now. Bob, being smart, keeps track of his payments in the following way.

Bob's notebook

C is the contractor here, B is Bob himself, Workers is Bob's worker, and let General is all the general costs he might have, say cement, rods etc. In the above image, each page of Bob depicts a page, created at a regular interval, one month. Each page contains the number of transactions in that month. There’s one important observation here. You can get to page 2 only when you’ve flipped through page 1, else there’s no other normal way to get there. This sequence of flipping through pages to advance in the notebook creates a chain of pages, so it's a Pagechain then? :)

Blockchain works similarly, each block being created at a certainly given interval, containing the data of every transaction that has been committed at that time duration, i.e., Bob paid worker 1 $30. Nounce is a special random number, generated by a miner when he mines (creates) a block. Other parameters are stored in a block, like block hash, page number, difficulty target, previous block hash, etc. But let's not get into that. A chain is built when multiple blocks are interconnected in such a way that you can’t get to the next block without going through the previous block. That’s a very high-level view of how blockchain works.

Step 1: The Basics — Building the Blocks

Imagine blockchain being a digital version of Bob's notebook. Before we get into creating pages (or blocks), let's define the base or what makes up a single block:
Data: The main part — transactions or information stored in the block. For example, “Bob paid worker 1 $30.”
Block Hash: A unique identifier for the block, like a uuid or fingerprint, is generated from its data.
Previous Block Hash: The “identifier” to the block before it.
Nonce: A special number used for validation in some systems.
Timestamp: The time the block was created, mostly in milliseconds.

Each block is similar to a page in Bob's notebook with important information making it unique and safe but now part of an even greater sequence.

Step 2: Linking the Blocks — Forming the Chain

See! A “block”chain.
Just like flipping through Bob's notebook in order, blocks in a blockchain are linked sequentially:
Start with the Genesis Block: This is the first block (page) and the foundation of the chain. It doesn’t have a “previous block.”
Add New Blocks: As new transactions are being added, create new blocks and connect them using the previous block’s hash.
Keep It Valid: Make sure that every block is properly linked by verifying the hashes. If any block is tampered with, the whole chain sequence breaks.

To make your blockchain tamper-proof:
Employ cryptographic hashing to produce unique block identifiers. A tiny change in a block completely changes its hash, resulting in a totally different chain. Store the hash of the previous block in the next block. This creates a dependency, so changing one block invalidates the entire chain.

Step 3: Decide the Rules — Adding New Blocks

A blockchain needs a system to agree on how new blocks are added. This is called a consensus mechanism (another great topic):
Proof of Work (PoW): Nodes (participants) solve complex puzzles to validate blocks (used by Bitcoin).
Proof of Stake (PoS): Validators are chosen based on their stake in the system (energy-efficient and widely adopted).

Mechanisms should be chosen based on one's goals — PoS is great for speed and efficiency, while PoW offers higher security.

Step 4: Make It Distributed — Adding Decentralization

The most important point of blockchain is to be decentralized, never letting the power be in a single hand. For a real blockchain experience, go beyond a single computer:
Use peer-to-peer (P2P) networking, so multiple nodes can share and sync the chain. Implement a system where nodes verify blocks and come into agreement on the correct version of the chain.

Enough talks, let's code one

Well, here you go. 🙃

import hashlib
import time
# Define the structure of a block
class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()
    def calculate_hash(self):
        block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}"
        return hashlib.sha256(block_string.encode()).hexdigest()
# Define the blockchain
class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]
    def create_genesis_block(self):
        return Block(0, time.time(), "Genesis Block", "0")
    def add_block(self, data):
        previous_block = self.chain[-1]
        new_block = Block(len(self.chain), time.time(), data, previous_block.hash)
        self.chain.append(new_block)
    def is_chain_valid(self):
        for i in range(1, len(self.chain)):
            current_block = self.chain[i]
            previous_block = self.chain[i - 1]
            if current_block.hash != current_block.calculate_hash():
                return False
            if current_block.previous_hash != previous_block.hash:
                return False
        return True
# Test your blockchain
my_blockchain = Blockchain()
my_blockchain.add_block("Bob paid worker 1 $30")
my_blockchain.add_block("Bob paid worker 2 $40")
for block in my_blockchain.chain:
    print(f"Index: {block.index}, Data: {block.data}, Hash: {block.hash}")
print("Is the Blockchain Valid?", my_blockchain.is_chain_valid())

Above is a very, very simplified version of a custom blockchain.

At its core, blockchain is a highly secure and decentralized system for recording and validating data, designed to ensure transparency and trust without relying on a central authority.

By now, we’ve created a simple blockchain from scratch. It may not compete with Ethereum or Bitcoin, but it’s a fantastic start! Ready to dive deeper or try adding advanced features? Let me know!